package com.polly.esphwevent.services;

import cn.hutool.core.util.StrUtil;
import com.polly.esphwevent.common.exceptions.AuthExceptionEnum;
import com.polly.esphwevent.common.exceptions.ServiceException;
import com.polly.esphwevent.common.jwtutils.JwtProperties;
import com.polly.esphwevent.common.jwtutils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;


@Service
public class EventValidateService {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    public boolean doValidate(HttpServletRequest request) {

        //获取token
        String tokenFromRequest = this.getTokenFromRequest(request);
        //校验token
        return this.validateToken(tokenFromRequest, request);
    }

    private String getTokenFromRequest(HttpServletRequest request){
        //获取token
        String authToken = request.getHeader("Authorization");
        if (StrUtil.isBlank(authToken)) {

            //如果header中没有token，则检查请求参数中是否带token
            authToken = request.getParameter("token");
            if (StrUtil.isBlank(authToken)) {
                throw new ServiceException(AuthExceptionEnum.TOKEN_EMPTY);
            }
        } else {
            authToken = authToken.substring("Bearer ".length());
        }

        return authToken;
    }

    private Boolean validateToken(String token, HttpServletRequest request){

        try {
            boolean flag = jwtTokenUtil.isTokenExpired(token);
            if (flag) {
                throw new ServiceException(AuthExceptionEnum.TOKEN_ERROR);
            } else {
                return true;
            }
        } catch (Exception e) {
            throw new ServiceException(AuthExceptionEnum.TOKEN_ERROR);
        }

    }




}
